package com.xuzimian.globaldemo.mq.rabbitmq.consumer;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.xuzimian.globaldemo.mq.rabbitmq.constants.Config;
import com.xuzimian.globaldemo.mq.rabbitmq.util.MqUtil;
import org.junit.jupiter.api.Test;

/***
 * @Description  rabbitmq 原生客户端，amqp协议的点对点(队列模式)的消费者
 * @author xzm
 *
 */
public class SimpleQueueConsumer {

    @Test
    public  void startConsumer() throws IOException, TimeoutException, InterruptedException {
        try (Connection conn = MqUtil.createSingletonConnection2()){
            Channel channel = conn.createChannel();

            // 设置客户端最多接收未被Ack的消息个数
            channel.basicQos(64);

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                        byte[] body) throws IOException {
                    System.out.println("接收到消息：" + new String(body));
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume("quote.CNH", consumer);
            // 等待回调函数执行完毕后，关闭资源
            TimeUnit.SECONDS.sleep(5);
            channel.close();
        }
    }



}